// 后端API基础路径 调用API时可引用该路径
var baseUrl = ''
if (location.hostname == 'localhost') {
    var baseUrl = 'http://app.ouyangpeng.top/app/poncon-cloud-disk/'
}
var webTitle = '鹏创云盘 - 不限速的免费云盘'
var userLoginDataKeyName = 'cloudDisk_UserLoginData'
var UserHasLogin = 0 // 用户已经登录？
var fileList = []
var isWorkFinished = 1 // 是否刚刚结束所有上传任务 是的话，再次选择文件会清空原列表，并恢复相关操作按钮
var hasLoadFileList = 1 // 下次访问fileManage页面是否加载文件列表
var isWorking = 0 // 是否处于正在上传的过程

var request_updateFileList = $.ajax()

function router(hash) {
    // 获取目标界面标识
    hash = hash.split('/')
    var target = hash[1]
    // 交换界面显示
    $('.page-oyp').hide()
    $('.page-' + target).fadeIn()
    $('.navbar-collapse li.active').removeClass('active')
    $('.navbar-collapse li.nav-item-' + target).addClass('active')
    // 判断目标界面标识 执行对应模块的载入事件
    if (target == 'home') {
        document.title = webTitle
        // 界面载入事件
        // ...
    } else if (target == 'about') {
        document.title = '关于 - ' + webTitle
        // 界面载入事件
        // ...
    } else if (target == 'login') {
        if (hash[2] == 'register') {
            $('.page-login input').val('')
            $('.page-login .page-sub-register').show()
            $('.page-login .title').html('用户注册')
            document.title = '用户注册 - ' + webTitle
        } else {
            $('.page-login .page-sub-login').show()
            $('.page-login .title').html('用户登录')
            document.title = '用户登录 - ' + webTitle
        }
        // 界面载入事件
        // ...
    } else if (target == 'fileManage') {
        document.title = '文件管理 - ' + webTitle
        // 界面载入事件
        // ...
        if (hasLoadFileList) {
            // hasLoadFileList = 0 // 每次进入fileManage都刷新列表
            $('.page-fileManage .loading').show()
            if (UserHasLogin || ifLogin()) {
                // 已经登录
                updateFileList(0)
            } else {
                $('.page-fileManage .loading').hide()
                $('.page-fileManage .msg_notLogin').show()
            }
        }

    } else {
        location.hash = '/home/'
    }
}
window.addEventListener('hashchange', function (event) {
    // 监听Hash改变 通过location.hash='xxx'可触发
    var hash = new URL(event.newURL).hash
    router(hash)
})

function hasLogin() {
    // 登陆成功时执行的事件
    var btn = $('.navbar-collapse li.nav-item-login a')
    btn.html('退出登录')
    btn.removeAttr('href')
    btn.unbind().click(function () {
        if (!confirm('确定要退出登录吗？')) {
            return
        }
        localStorage[userLoginDataKeyName] = ''
        notLogin()
    })
    UserHasLogin = 1
}


function notLogin() {
    // 未登录时执行的事件
    localStorage[userLoginDataKeyName] = ''
    var btn = $('.navbar-collapse li.nav-item-login a')
    btn.html('登录 / 注册')
    btn.unbind().click(function () {
        location.hash = '/login/'
    })
    location.hash = '/login/'
    UserHasLogin = 0
}
function ifLogin() {
    try {
        var userdata = JSON.parse(localStorage[userLoginDataKeyName])
        if (userdata.username && userdata.password && userdata.email) {
            var success = 0
            $.ajax({
                url: baseUrl + './api/login.php',
                method: 'post',
                data: {
                    username: userdata.username,
                    password: userdata.password
                },
                success: function (data) {
                    if (data.code == 200) {
                        // 登录成功
                        hasLogin()
                        localStorage[userLoginDataKeyName] = JSON.stringify(data.result)
                        success = 1
                    } else {
                        notLogin()
                        success = 0
                    }
                },
                async: false
            })
            if (success) {
                return true
            } else {
                return false
            }
        } else {
            notLogin()
            return false
        }
    } catch (error) {
        notLogin()
        return false
    }
}

function fileSize(a) {
    var d = ["B", "KB", "MB", "GB", "TB", "PB"];
    var e = 1024;
    for (var b = 0; b < d.length; b++) {
        if (a < e) {
            return (b == 0 ? a : a.toFixed(2)) + d[b]
        }
        a /= e
    }
}

function getUserInfo(keyName) {
    try {
        var userdata = JSON.parse(localStorage[userLoginDataKeyName])
        return userdata[keyName]
    } catch (error) {
        return null
    }
}


// 上传文件
function uploadFile(fileList, index) {
    isWorking = 1
    $('.page-home span.fileNum').html('正在上传：' + (index + 1) + ' / ' + fileList.length)
    var formData = new FormData()
    var fileData = fileList[index]
    var startTime = new Date().getTime()
    formData.append('file', fileData)
    formData.append('name', fileData.name)
    formData.append('puid', getUserInfo('token')[0])
    formData.append('_token', getUserInfo('token')[1])
    var ele = $('.page-home .workList .workListItem')[index] // 获取当前列表项
    var request = $.ajax({
        method: 'post',
        url: 'http://pan-yz.chaoxing.com/upload',
        data: formData,
        cache: false,
        processData: false,
        contentType: false,
        dataType: 'json',
        error: function (e) {
            alert('出错：' + e.statusText)
        },
        success: function (data) {
            // 上报文件信息
            var objectId = data.objectId
            if (!objectId) {
                $(ele).find('.remainingTime').html(data.msg)
                $(ele).find('.upload-status').html('')
                if (++index < fileList.length) {
                    uploadFile(fileList, index)
                } else {
                    // 上传出错
                    isWorkFinished = 1
                    $('.page-home button.allCancel').html('清空列表').show()
                    $('.page-home span.fileNum').html('全部上传完成')
                    $(ele).find('.text-secondary').removeClass('text-secondary').addClass('text-danger')
                    $(ele).find('.bg-secondary').removeClass('bg-secondary').addClass('bg-danger')
                    isWorking = 0
                }
                return
            }
            $.ajax({
                method: 'post',
                url: baseUrl + './api/addFile.php',
                data: {
                    username: getUserInfo('username'),
                    password: getUserInfo('password'),
                    name: fileData.name,
                    size: fileData.size,
                    type: fileData.type,
                    objectId: data.objectId
                },
                contentType: 'application/x-www-form-urlencoded',
                dataType: 'json',
                success: function (data) {
                    if (data.code == 200) {
                        $(ele).find('.remainingTime').html('上传完成')
                        $(ele).find('a.copybtn').unbind().click(function () {
                            $('.copy_temp').attr('data-clipboard-text', objectId)
                            $('.copy_temp').click()
                        })
                        $(ele).find('.upload-status').html(fileSize(fileData.size))
                        $(ele).find('.text-secondary').removeClass('text-secondary').addClass('text-success')
                        $(ele).find('.bg-secondary').removeClass('bg-secondary').addClass('bg-success')
                    } else {
                        $(ele).find('.remainingTime').html(data.msg)
                        $(ele).find('.upload-status').html(fileSize(fileData.size))
                    }
                    if (++index < fileList.length) {
                        uploadFile(fileList, index)
                    } else {
                        // 全部上传完成
                        isWorkFinished = 1
                        $('.page-home button.allCancel').html('清空列表').show()
                        $('.page-home span.fileNum').html('全部上传完成')
                        isWorking = 0
                    }
                }
            })
        },
        xhr: function () {
            var xhr = $.ajaxSettings.xhr()
            if (xhr.upload) {
                xhr.upload.addEventListener('progress', function (e) {
                    var percentage = parseInt(e.loaded / e.total * 100) // 单位B
                    $(ele).find('.progress-bar').css('width', percentage + '%').html(percentage + '%')
                    $(ele).find('.upload-status').html(fileSize(e.loaded) + ' / ' + fileSize(e.total))
                    var speed = fileSize(e.loaded / ((new Date().getTime() - startTime) / 1000))
                    $(ele).find('.remainingTime').html('<span class="d-none d-sm-inline">正在上传：</span>' + speed + '/s')
                    // 10KB/1M    65KB/s
                }, false)
            }
            return xhr
        }
    })
}

// 时间戳解析转换
function parseDate(date) {
    function two(t) {
        if (t < 10) {
            return '0' + t
        }
        return t
    }
    date = new Date(date)
    return two(date.getFullYear())
        + '-' + two(date.getMonth() + 1)
        + '-' + two(date.getDate())
        + ' ' + two(date.getHours())
        + ':' + two(date.getMinutes())
}

// 更新文件列表
function updateFileList(offset) {
    if (offset == 0) {
        $('.page-fileManage .fileList').html('')
    }
    $('.page-fileManage .loading').show()
    $('.page-fileManage .loadMore').hide()
    request_updateFileList.abort()
    request_updateFileList = $.ajax({
        method: 'post',
        url: baseUrl + './api/getFileList.php',
        data: {
            username: getUserInfo('username'),
            password: getUserInfo('password'),
            offset: offset,
            pageSize: 24
        },
        contentType: 'application/x-www-form-urlencoded',
        dataType: 'json',
        success: function (data) {
            var used_capacity = data.used_capacity
            var total_capacity = data.total_capacity
            $('.page-fileManage .capacityInfo .item').html('空间使用情况：' + fileSize(used_capacity * 1024) + ' / ' + fileSize(total_capacity * 1024))
            $('.page-fileManage .capacityInfo .progress-bar').css('width', (used_capacity / total_capacity * 100) + '%')
            if (data.code == 200) {
                $('.page-fileManage .loading').hide()
                var list = data.result
                if (list.length == 0) {
                    var msg = offset == 0 ? '文件列表为空' : '已经到底了'
                    $('.page-fileManage .loadMore button').attr('disabled', 'disabled').html(msg)
                    $('.page-fileManage .loadMore').show()
                    return
                }
                var html = ''
                for (var i = 0; i < list.length; i++) {
                    html += '<div class="col-lg-4 col-md-6">\
                                <div class="p-3 rounded border border-secondary shadow mb-4 listItem">\
                                    <h5 class="mr-auto mb-2 text-nowrap text-truncate">' + list[i].name + '</h5>\
                                    <div class="d-flex">\
                                        <div class="upload_time mr-auto">' + parseDate(list[i].upload_time * 1000) + '</div>\
                                        <div class="size">' + fileSize(list[i].size) + '</div>\
                                    </div>\
                                    <div class="btns" data-objectid="' + list[i].objectId + '" data-type="' + list[i].type + '">\
                                        <button class="btn btn-sm btn-success mr-2 mt-2 download">下载</button>\
                                        <button class="btn btn-sm btn-danger mr-2 mt-2 delete">删除</button>\
                                        <button class="btn btn-sm btn-info mt-2 info">文件信息</button>\
                                    </div>\
                                </div>\
                            </div>'
                }
                $('.page-fileManage .fileList').append(html)
                $('.page-fileManage .loadMore').show()
                $('.page-fileManage .loadMore button').removeAttr('disabled').html('加载更多')
                $('.page-fileManage .loadMore').unbind().click(function () {
                    updateFileList($('.page-fileManage .fileList .listItem').length)
                })
                $('.page-fileManage .fileList .btns button.download').unbind().click(function () {
                    var objectId = $(this).parent().data('objectid')
                    var downloadUrl = 'http://sharewh1.xuexi365.com/share/download/' + objectId
                    // window.open(downloadUrl)
                    $('.downloads_iframe').append('<iframe src="' + downloadUrl + '"></iframe>')
                    // $('#iframe').attr('src', downloadUrl)
                })
                $('.page-fileManage .fileList .btns button.delete').unbind().click(function () {
                    if (!confirm('确定要删除该文件吗？')) {
                        return
                    }
                    $(this).attr('disabled', 'disabled')
                    var objectId = $(this).parent().data('objectid')
                    var ele = $(this)
                    $.ajax({
                        method: 'post',
                        url: baseUrl + './api/deleteFile.php',
                        data: {
                            username: getUserInfo('username'),
                            password: getUserInfo('password'),
                            objectId: objectId
                        },
                        contentType: 'application/x-www-form-urlencoded',
                        dataType: 'json',
                        success: function (data) {
                            if (data.code == 200) {
                                ele.parent().parent().parent().remove()
                                if ($('.page-fileManage .fileList .listItem').length == 0) {
                                    updateFileList(0)
                                }
                            } else {
                                alert(data.msg)
                                $('.page-fileManage .fileList .btns button.delete').removeAttr('disabled')
                            }
                        }
                    })
                })
                $('.page-fileManage .fileList .btns button.info').unbind().click(function () {
                    var objectId = $(this).parent().data('objectid')
                    var type = $(this).parent().data('type')
                    var ele = $(this).parent().parent()
                    var html = ''
                    var list = [ele.find('h5').html(), ele.find('.size').html(), ele.find('.upload_time').html(), type, objectId]
                    var nameList = ['文件名称', '文件大小', '上传时间', '文件类型', '文件ID']
                    for (var i = 0; i < list.length; i++) {
                        html += '<div class="row mb-2">\
                                    <div class="col-4 col-sm-3 font-weight-bold text-right text-nowrap">' + nameList[i] + '</div>\
                                    <div class="col-8 col-sm-9 name">' + list[i] + '</div>\
                                </div>'
                    }
                    $('.modal-shareFile .infoList').html(html)
                    var j1 = location.pathname.split('/')
                    var j2 = j1[j1.length - 1]
                    var j3 = new RegExp('/' + j2 + '$')
                    var url = location.pathname.replace(j3, '/')
                    $('.modal-shareFile .input-downloadUrl').val(location.origin + url + 'api/download.php?objectId=' + objectId)
                    var downloadUrl = 'http://sharewh1.xuexi365.com/share/download/' + objectId
                    $('.modal-shareFile img.download_url_qcode').attr('src', '')
                    $('.modal-shareFile img.download_url_qcode').attr('src', 'http://qcode.16q.cn/code.jspx?s=3&url=' + encodeURIComponent(downloadUrl))
                    $('.modal-shareFile').modal('show')
                })
            } else {
                alert(data.msg)
            }
        }
    })
}

function addFile(fileDatas) {
    // 检测到文件列表，向页面中增加列表项
    var html = ''
    for (var i = 0; i < fileDatas.length; i++) {
        if (fileList.length == 100) {
            alert('最多允许同时上传100个文件')
            break
        }
        // 判断文件是否重复
        if (fileList.find(function (value) {
            var list = ['name', 'size', 'lastModified'] // 需要比较的项目
            var flag = 1
            for (var j = 0; j < list.length; j++) {
                if (fileDatas[i][list[j]] != value[list[j]]) {
                    flag = 0
                }
            }
            return flag
        })) {
            continue
        } else if (fileDatas[i].size == 0) {
            alert('选中的文件中包含空文件，已过滤')
            continue
        }
        fileList.push(fileDatas[i])
        html += '<div class="col-lg-6 workListItem">\
                    <div class="border border-secondary shadow p-3 rounded mb-4">\
                        <div class="d-flex align-items-center mb-3">\
                            <h5 class="mr-auto mb-0 text-nowrap text-truncate">' + fileDatas[i].name + '</h5>\
                            <button type="button" class="close" title="移除改文件" data-info="' + fileDatas[i].name + '|' + fileDatas[i].size + '|' + fileDatas[i].lastModified + '">\
                                <span>&times;</span>\
                            </button>\
                        </div>\
                        <div class="progress mb-2">\
                            <div class="progress-bar progress-bar-striped bg-secondary" role="progressbar"\
                                style="width: 0%;"></div>\
                        </div>\
                        <div class="d-flex text-secondary">\
                            <div class="mr-auto upload-status">' + fileSize(fileDatas[i].size) + '</div>\
                            <div class="remainingTime">\
                                等待上传\
                            </div>\
                        </div>\
                    </div>\
                </div>'
    }
    $('.page-home .workList').append(html)
    $('.page-home span.fileNum').html('文件数量：' + fileList.length)
    $('.page-home input.input-file').val('')
    $('.page-home .workList .workListItem button.close').unbind().click(function () {
        var ele = $(this)
        ele2 = ele.parent().parent().parent()
        ele2.remove()
        var index_good
        fileList.find(function (value, index) {
            var list = ['name', 'size', 'lastModified'] // 需要比较的项目
            var item = ele.data('info').split('|')
            var flag = 1
            for (var j = 0; j < list.length; j++) {
                if (item[j] != value[list[j]]) {
                    flag = 0
                }
            }
            if (flag) {
                index_good = index
            }
            return flag
        })
        fileList.splice(index_good, 1)
        $('.page-home span.fileNum').html('文件数量：' + fileList.length)
        if (!fileList.length) {
            $('.page-home .btns').hide()
        }
    })
}
$(document).ready(function () {
    if (!location.hash.split('/')[1]) {
        history.replaceState({}, null, '#/home/')
    }
    router(location.hash)
    // 公共载入事件
    // ...

    ifLogin()


    $('.navbar-collapse li').click(function () {
        var ele = $('.navbar button.navbar-toggler')
        if (ele.css('display') == 'block') {
            $('.navbar button.navbar-toggler').click()
        }
    })

    $('.page-login button.reset').click(function () {
        $('.page-login input').val('')
    })


    function validation_register(data, mode) {
        // mode 1:验证整个注册页表单 2: 跳过验证码字段
        data.username = $('.page-login .page-sub-register .input-username').val()
        data.email = $('.page-login .page-sub-register .input-email').val()
        data.password = $('.page-login .page-sub-register .input-password').val()
        var password2 = $('.page-login .page-sub-register .input-password2').val()
        data.verCode = $('.page-login .page-sub-register .input-verCode').val()
        if (!data.username.match(/^\w{4,20}$/)) {
            alert('用户名要求长度为4-20，只能包含数字、字母和下划线')
            return false
        } else if (!data.email.match(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/)) {
            alert('邮箱不合法')
            return false
        } else if (!data.password.match(/^\w{8,20}$/)) {
            alert('密码要求长度为8-20，只能包含数字、字母和下划线')
            return false
        } else if (data.password != password2) {
            alert('两次输入的密码不一致')
            return
        } else if (!data.verCode && mode == 1) {
            alert('请输入验证码')
            return false
        }
        return true
    }

    $('.page-login .page-sub-register button.register').click(function () {
        var data = {}
        if (!validation_register(data, 1)) {
            return
        }
        var username = data.username
        var password = data.password
        $.ajax({
            method: 'post',
            url: baseUrl + './api/register.php',
            data: {
                username: username,
                password: md5(password),
                email: data.email,
                verCode: data.verCode
            },
            contentType: 'application/x-www-form-urlencoded',
            dataType: 'json',
            success: function (data) {
                if (data.code == 200) {
                    location.hash = '/login/'
                    console.log(username, password)
                    $('.page-login .page-sub-login .input-username').val(username)
                    $('.page-login .page-sub-login .input-password').val(password)
                } else {

                }
                alert(data.msg)
            }
        })
    })

    $('.page-login .page-sub-register button.getVerCode').click(function () {
        var data = {}
        if (!validation_register(data, 2)) {
            return
        }
        var ele = $(this)
        ele.attr('disabled', 'disabled')
        $.ajax({
            method: 'post',
            url: baseUrl + './api/getCode.php',
            data: {
                email: data.email
            },
            contentType: 'application/x-www-form-urlencoded',
            dataType: 'json',
            success: function (data) {
                if (data.code == 200) {
                    for (var i = 0; i < 60; i++) {
                        (function (i) {
                            setTimeout(function () {
                                ele.html(60 - i + '秒后重新获取')
                            }, 1000 * i)
                        }(i))
                    }
                    setTimeout(() => {
                        ele.removeAttr('disabled')
                        ele.html('获取验证码')
                    }, 1000 * 60);
                } else {
                    alert(data.msg)
                    ele.removeAttr('disabled')
                    ele.html('获取验证码')
                }
            }
        })
    })

    $('.page-login .page-sub-login button.login').click(function () {
        var username = $('.page-login .page-sub-login .input-username').val()
        var password = $('.page-login .page-sub-login .input-password').val()
        if (!username || !password) {
            alert('账号和密码不能为空')
            return
        } else if ((!username.match(/^\w{4,20}$/)
            && !username.match(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/))
            || !password.match(/^\w{8,20}$/)) {
            alert('账号或密码格式错误')
            return
        }
        $.ajax({
            method: 'post',
            url: baseUrl + './api/login.php',
            data: {
                username: username,
                password: md5(password)
            },
            contentType: 'application/x-www-form-urlencoded',
            dataType: 'json',
            success: function (data) {
                if (data.code == 200) {
                    // 登录成功
                    localStorage[userLoginDataKeyName] = JSON.stringify(data.result)
                    location.hash = '/home/'
                    hasLogin()
                } else {
                    alert(data.msg)
                }
            }
        })
    })
    $('.page-login .page-sub-login .input-password').bind('keyup', function (event) {
        if (event.keyCode == 13) {
            $(this).blur()
            $('.page-login .page-sub-login button.login').click()
        }
    })
    $('.page-login .page-sub-register .input-verCode').bind('keyup', function (event) {
        if (event.keyCode == 13) {
            $(this).blur()
            $('.page-login .page-sub-register button.getVerCode').click()
        }
    })
    $('.page-home button.btn-input-file').click(function () {
        $('.page-home input.input-file').click()
    })
    $('.page-home input.input-file').change(function () {
        // 没有登录，无法添加文件，转到登录
        if (!UserHasLogin) {
            location.hash = '/login/'
            $('.page-home input.input-file').val('')
            return
        }
        if (isWorking) {
            $('.page-home input.input-file').val('')
            return
        }
        $('.page-home .btns').show()
        var fileDatas = $(this).prop('files')
        if (!fileDatas.length) {
            $('.page-home input.input-file').val('')
            return
        }

        if (isWorkFinished) {
            isWorkFinished = 0
            // 刚刚完成任务，此时新增文件，直接清空原列表，并恢复按钮
            $('.page-home .workList').html('')
            fileList = []
            $('.page-home button.allUpload').show()
            $('.page-home button.allCancel').html('全部取消')
        }

        addFile(fileDatas)
    })
    $('.page-home button.allCancel').click(function () {
        if (!isWorkFinished && !confirm('确定要清空文件列表吗？')) {
            return
        }
        fileList = []
        $('.page-home .workList').html('')
        $('.page-home .btns').hide()
    })

    $('.nav-item-fileManage a').click(function () {
        if (!UserHasLogin) {
            location.hash = '/login/'
            return
        }
        location.hash = '/fileManage/'
    })

    $('.page-home button.allUpload').click(function () {
        $('.page-home .btns button').hide()
        $('.page-home .workList .workListItem button.close').hide()
        uploadFile(fileList, 0)
    })


    // 文件拖拽上传
    $('.page-home .upload-box-box')[0].addEventListener('dragover', function (event) {
        event.preventDefault()
    })
    $('.page-home .upload-box-box')[0].addEventListener('drop', function (event) {
        event.preventDefault()
        // 没有登录，无法添加文件，转到登录
        if (!UserHasLogin) {
            location.hash = '/login/'
            return
        }
        if (isWorking) {
            console.log('当前有任务在进行，无法添加文件')
            return
        }
        $('.page-home .btns').show()
        var fileDatas = event.dataTransfer.files
        if (!fileDatas.length) {
            return
        }

        if (isWorkFinished) {
            isWorkFinished = 0
            // 刚刚完成任务，此时新增文件，直接清空原列表，并恢复按钮
            $('.page-home .workList').html('')
            fileList = []
            $('.page-home button.allUpload').show()
            $('.page-home button.allCancel').html('全部取消')
        }

        addFile(fileDatas)
    })

    // 联系客服
    $('.page-fileManage .addCapacity').click(function () {
        if ('ontouchstart' in document.documentElement) {
            // 移动端
            window.open('https://qm.qq.com/cgi-bin/qm/qr?k=OWeeT0kf-xyO97hmZ27inm-9c98kvSxU&noverify=0')
        } else {
            window.open('tencent://message/?uin=2329632875')
        }
    })
    $('body').show()
    $('a').attr('draggable', 'false')
    new ClipboardJS('.copybtn')
})